package main

import (
	"net/http"
	"os"
	"time"
	"context"
	"strconv"
	// "fmt"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"

	"night-school-api/database"
	"night-school-api/models"
	"night-school-api/handlers"
	"night-school-api/handlers/admin"
	"night-school-api/middlewares"
	"night-school-api/utils"
	"night-school-api/pkg/redis"
	"night-school-api/pkg/taskq"
	"night-school-api/job"
)

var JobQueue *job.JobQueue

func main() {
	// os.Setenv("MYSQL_DSN", "project_user:pu-skk129l-91291--12aa@tcp(127.0.0.1:3309)/night_school?charset=utf8mb4&parseTime=True&loc=Asia%2FShanghai")
	// os.Setenv("MINIPROGRAM_APP_ID", "wx138c83b9e10ec4c0")
	// os.Setenv("MINIPROGRAM_SECRET", "94fabd27e12223653e07b7230215253b")
	// os.Setenv("JWT_SECRET", "Kf8YhOXmYk5zwi6pvG+MP2oIR86YpRI90g4UHgZzhzA=")
	// os.Setenv("STATIC_RESOURCE_URL", "http://192.168.2.162:1324/static/")

	// fmt.Printf("redis_conn: %s", os.Getenv("REDIS_CONN"))

	// 初始化Redis连接
	redisDb, err := strconv.Atoi(os.Getenv("REDIS_DB"))
	if err != nil {
		redisDb = 0
	}
	rc := redis.New(os.Getenv("REDIS_CONN"), os.Getenv("REDIS_PASS"), redisDb)
	// 初始化定时任务队列
	taskManager := taskq.NewManager(rc)
	taskManager.RegisterHandler("course_start", job.HandleCourseStartJob)
	
	
	// 启动定时任务后台消费者
	ctx := context.Background()
	go taskManager.StartConsumer(ctx, job.CourseStartJobRedisKey)

	// 定时任务队列服务
	JobQueue = job.NewJobQueue(rc)
	admin.JobQueue = JobQueue



	// 初始化数据库连接
	database.InitDB()
	defer database.CloseDB()

	e := echo.New()
	e.Debug = true

	e.Validator = utils.NewCustomValidator()

	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, ":)")
	})

	e.Static("/static", "uploads")

	/**
	 * 小程序接口
	 */
	mnpApi := e.Group("/mnp")
	mnpApi.POST("/login", handlers.MnpLogin)
	mnpApi.GET("/simulate-login", handlers.SimulateLogin)

	mnpApi.GET("/test-send-course-start-sub-msg", func(c echo.Context) error {
		idStr := c.QueryParam("id")
		id, err := strconv.Atoi(idStr)
		if err != nil || id <= 0 {
			return utils.JSONError(c, "id 错误")
		}

		taskID := "course_start:" + idStr
		exp :=  time.Now().In(models.TimeLocation).Add(5 * time.Second)
		err = JobQueue.CreateCourseStartJob(c.Request().Context(), taskID, exp)
		if err != nil {
			return utils.JSONError(c, "err:" + err.Error())
		} else {
			return utils.JSONSuccess(c, nil, "定时任务添加成功")
		}
	})


	// 不需要登录
	dictApi := mnpApi.Group("/dict")
	// 配置 CORS 中间件
	dictApi.Use(middleware.CORS())
	dictApi.GET("/cates", handlers.GetCourseCates)
	dictApi.GET("/counties", handlers.GetCounties)
	dictApi.GET("/global-notification", admin.GetGlobalNotification)


	// 需要登录
	mnpLogedinApi := mnpApi.Group("")
	mnpLogedinApi.Use(middlewares.JwtMiddleware(), middlewares.CheckRoleMiddleware("user"))
	mnpLogedinApi.POST("/phone", handlers.MnpGetPhone)
	mnpLogedinApi.GET("/tmpl", handlers.MnpTmpl)
	mnpLogedinApi.POST("/sub-msg-accept", handlers.MnpSubscribeMsgAccept)
	

	// 可选登录
	courseListApi := mnpApi.Group("/course")
	courseListApi.Use(middlewares.OptionalJWTMiddleware)
	courseListApi.GET("", handlers.GetCourses)
	courseListApi.GET("/detail", handlers.CourseDetail)

	
	// 需要登录
	courseApi := mnpApi.Group("/course")
	courseApi.Use(middlewares.JwtMiddleware(), middlewares.CheckRoleMiddleware("user"))
	courseApi.POST("/add", handlers.CreateCourse) // 创建课程
	courseApi.POST("/enroll", handlers.Enroll)	// 报名
	courseApi.POST("/cancel-enroll", handlers.CancelEnroll) // 取消报名
	
	courseApi.POST("/comment", handlers.Comment)  // 评论课程
	courseApi.GET("/my-course", handlers.MyCourses)  // 我的课程
	courseApi.GET("/teacher-course", handlers.TeacherCourses)  // 作为老师的课程


	userApi := mnpApi.Group("/user")
	userApi.Use(middlewares.JwtMiddleware(), middlewares.CheckRoleMiddleware("user"))
	userApi.POST("/update-profile", handlers.UpdateProfile)
	userApi.POST("/upload-avatar", handlers.UploadAvatar)
	userApi.POST("/suggest", handlers.Suggest)
	
	userApi.GET("/refresh-login", handlers.RefreshLogin)


	/**
	 * 后台接口
	 * 
	 */
	adminApi := e.Group("/admin")

	// 配置 CORS 中间件
	adminApi.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		// 允许的来源（生产环境应指定具体域名）
		AllowOrigins: []string{"*"},
		
		// 允许的 HTTP 方法
		AllowMethods: []string{
			echo.GET, 
			echo.POST, 
			echo.HEAD,
			echo.OPTIONS,
		},
		
		// 允许的请求头
		AllowHeaders: []string{"*"},
		
		// 是否允许携带凭证（cookies）
		AllowCredentials: true,
		
		// 预检请求缓存时间（秒）
		MaxAge: 86400,
	}))


	adminApi.POST("/login", admin.AdminLogin)

	// 需要登录
	adminApi.Use(middlewares.JwtMiddleware(), middlewares.CheckRoleMiddleware("admin"))
	
	adminApi.GET("/admins", admin.GetAdmins)
	adminApi.POST("/admin/update", admin.UpdateAdmin)
	adminApi.POST("/admin/delete", admin.DeleteAdmin)

	adminApi.GET("/users", admin.GetUsers)

	adminApi.GET("/courses", admin.GetCourses)
	adminApi.POST("/course/update", admin.UpdateCourseStatus)
	adminApi.POST("/course/update-all", admin.UpdateCourse)
	adminApi.POST("/course/upload-cover", admin.UploadCover)
	adminApi.POST("/course/delete", admin.DeleteCourse)

	adminApi.GET("/course/enrollments", admin.GetEnrollments)
	adminApi.POST("/course/enrollment/update", admin.UpdateEnrollment)

	
	adminApi.GET("/course/comments", admin.GetComments)
	
	adminApi.GET("/global-notification", admin.GetGlobalNotification)
	adminApi.POST("/global-notification/update", admin.UpdateGlobalNotification)
	adminApi.POST("/global-notification/delete", admin.DeleteGlobalNotification)

	adminApi.GET("/statistic", admin.GetStatistic)
	

	e.Logger.Fatal(e.Start(":1323"))
}
